package com.lcj.eduService.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lcj.eduService.entity.EduSubject;
import com.lcj.eduService.entity.excel.ExcelSubjectData;
import com.lcj.eduService.service.EduSubjectService;
import com.lcj.servicebase.config.exceptionHandler.EduException;

/**
 * @Author：LCJ
 * @Description：
 * @Date：Create in 20:43 2021/3/10 0010
 */

public class SubjectListener extends AnalysisEventListener<ExcelSubjectData> {

    //因为该class不由spring管理，所以需要手动注入
    public EduSubjectService eduSubjectService;

    public SubjectListener() {
    }

    public SubjectListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    //读取内容
    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
        if(excelSubjectData == null){
            throw new EduException(2001,"文件数据为空");
        }
        //一行一行读取，每次读取两个值，第一个值一级分类，第二个值二级分类
        //判断一级分类是否重复
        EduSubject existOneSubject=this.existOneSubject(eduSubjectService,excelSubjectData.getOneSubjectName());
        if(existOneSubject == null){//没有相同一级分类，进行添加
            existOneSubject.setParentId("0");
            existOneSubject.setTitle(excelSubjectData.getOneSubjectName());
            eduSubjectService.save(existOneSubject);
        }

        //添加二级分类
        String pid=existOneSubject.getId();
        EduSubject existTwoSubject=this.existTwoSubject(eduSubjectService,excelSubjectData.getTwoSubjectName(),pid);
        if(existTwoSubject == null){
            existTwoSubject = new EduSubject();
            existTwoSubject.setParentId(pid);
            existTwoSubject.setTitle(excelSubjectData.getTwoSubjectName());
            eduSubjectService.save(existTwoSubject);
        }

    }

    //判断一级分类不能重复添加
    private EduSubject existOneSubject(EduSubjectService subjectService, String name){
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject oneSubject=subjectService.getOne(wrapper);
        return oneSubject;
    }

    //判断二级分类不能重复添加
    private EduSubject existTwoSubject(EduSubjectService subjectService, String name,String pid){
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject oneSubject=subjectService.getOne(wrapper);
        return oneSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
